package com.qf.controller;


import com.alibaba.fastjson.JSON;
import com.qf.pojo.*;
import com.qf.service.AddressService;
import com.qf.service.AreaService;
import com.qf.service.CartService;
import com.qf.service.GoodsService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.AreaServiceImpl;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.DBTools;
import com.qf.utils.SYS;
import com.qf.vo.MsgResult;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;


public class CartController extends Base {
    private GoodsService goodsService=new GoodsServiceImpl();
    private CartService cartService=new CartServiceImpl();
    private AreaService areaService=new AreaServiceImpl();
    private AddressService addressService=new AddressServiceImpl();



    public ShopCart getShopCart(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session=req.getSession();
        Object obj=session.getAttribute(SYS.CART);
        if (obj!=null&obj instanceof ShopCart) {
            return (ShopCart) obj;
        }
        return null;
    }

    public User getUser(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session=req.getSession();
        Object obj=session.getAttribute(SYS.USER);
        if (obj!=null&obj instanceof User) {
            return (User) obj;
        }
        return null;
    }

    //添加购物车
    public String add(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("cartcontroller...start");

        String gids=req.getParameter("gid");
        Integer gid=Integer.valueOf(gids);
        Goods goods=goodsService.getDetailById(gid);
        ShopCart shopCart=this.getShopCart(req,resp);

        int res=shopCart.add(goods);
        MsgResult msg=new MsgResult();

        if (res==1){
            msg.setCode(1);
            msg.setMsg("商品："+goods.getName()+"成功添加到购物车!");
            String str= JSON.toJSONString(msg);
            return str;
        }
        msg.setCode(0);
        msg.setMsg("商品："+goods.getName()+"添加到购物车失败!");
        String str= JSON.toJSONString(msg);
        return str;
    }


    //查看购物车内所有商品
    public String showCart(HttpServletRequest req, HttpServletResponse resp){
        ShopCart shopCart=this.getShopCart(req,resp);
        Collection<ShopItem>  items=shopCart.show();
        req.setAttribute(SYS.CART,items);
        return "z:cart.jsp";
    }

    //修改购物车某个商品的数量
    public String updateCart(HttpServletRequest req, HttpServletResponse resp){
        ShopCart shopCart=this.getShopCart(req,resp);
        Integer gid=Integer.valueOf(req.getParameter("gid"));
        Integer flag=Integer.valueOf(req.getParameter("flag"));
        int num=shopCart.updateNum(gid,flag);
        return "{\"num\":"+num+"}";
    }

    //删除购车内的一项商品
    public String deleteOne(HttpServletRequest req, HttpServletResponse resp) {
        Integer gid = Integer.valueOf(req.getParameter("gid"));
        ShopCart shopCart = this.getShopCart(req, resp);
        User user = this.getUser(req, resp);
        MsgResult msg = new MsgResult();

        //先删会话，再删数据库
        if (shopCart != null && user != null) {
            try {
                //开启事务的手动提交
                DBTools.startTransaction();
                int res=cartService.deleteOne(user.getId(),gid);
                if (res==1) {
                    ShopItem shopItem = shopCart.deleteOne(gid);
                    if(shopItem != null){
                        msg.setCode(1);
                        msg.setMsg("商品：" + shopItem.getGoods().getName() + "成功删除!");

                        //会话及数据路都删除成功，提交事务
                        DBTools.commit();
                    }
                }
            } catch (Exception e) {
                //回滚事务
                DBTools.rollback();
                msg.setCode(0);
                msg.setMsg("商品删除失败!请刷新");
                e.printStackTrace();
            }finally {
                String str = JSON.toJSONString(msg);
                return str;
            }
        }
        msg.setCode(0);
        msg.setMsg("数据异常!请刷新");
        String str = JSON.toJSONString(msg);
        return str;
    }

    //生成订单预览
    public String generate(HttpServletRequest req, HttpServletResponse resp){
        String[] gids=req.getParameterValues("ids");
        ShopCart shopCart=this.getShopCart(req,resp);
        MsgResult<ShopItem> msg=shopCart.show(gids);
        List<Area> provinceList=areaService.getProvince(null);

        HttpSession session=req.getSession();
        Object obj=session.getAttribute(SYS.USER);
        if (obj!=null&& obj instanceof User){
            User user=(User)obj;
            Integer uid=user.getId();
            List<Address> addressList= addressService.listAll(uid);
            req.setAttribute("addreslist",addressList);
            req.setAttribute("items",msg.getItemList());
            req.setAttribute("total",msg.getTotal());
            req.setAttribute(SYS.PROVINCES,provinceList);
            return "z:order.jsp";
        }
        return "错误";
    }
}
